#! /usr/bin/env python
# -*- coding: utf-8 -*-

# *************************************************************
#  Copyright (c) Huoty - All rights reserved
#
#      Author: Huoty <sudohuoty@gmail.com>
#  CreateTime: 2017-06-15 19:18:35
# *************************************************************

from __future__ import print_function

import os
import time
from datetime import datetime, timedelta

from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.jobstores.memory import MemoryJobStore
from apscheduler.jobstores.sqlalchemy import SQLAlchemyJobStore
from apscheduler.executors.pool import ThreadPoolExecutor, ProcessPoolExecutor
from apscheduler.events import EVENT_JOB_MISSED, EVENT_JOB_ERROR


def tick():
    print('Tick! The time is: %s' % datetime.now())

def cron_job(task):
    print("I was running, task is: {}, current time is: {}".format(task, datetime.now()))

def error_listener(event):
    print("-" * 120)
    print(dir(event))
    print("-" * 120)


jobstores = {
    'default': MemoryJobStore(),
    #'sqlalchemy': SQLAlchemyJobStore(url='sqlite:////home/huayong/temp/apscheduler-jobstore.sqlite')
}
executors = {
    'default': ThreadPoolExecutor(2),
}

job_defaults = {
    'coalesce': False,
    'max_instances': 2,
}


if __name__ == '__main__':
    import logging
    logging.basicConfig()

    scheduler = BackgroundScheduler(jobstores=jobstores, executors=executors, job_defaults=job_defaults)
    scheduler.add_listener(error_listener, EVENT_JOB_MISSED | EVENT_JOB_ERROR)
    scheduler.add_job(tick, 'interval', seconds=5)
    scheduler.start()
    print('Press Ctrl+{0} to exit'.format('Break' if os.name == 'nt' else 'C'))

    print("Add extra job...")
    run_date = datetime(2017, 6, 21, 11, 40)
    for task in xrange(1, 10000):
        scheduler.add_job(cron_job, "date", run_date=run_date, args=[task], misfire_grace_time=300)
        # scheduler.add_job(cron_job, "date", run_date=datetime.now()+timedelta(minutes=1), args=[task])

    print("job list:")
    scheduler.print_jobs()

    try:
        # This is here to simulate application activity (which keeps the main thread alive).
        while True:
            time.sleep(2)
    except (KeyboardInterrupt, SystemExit):
        # Not strictly necessary if daemonic mode is enabled but should be done if possible
        scheduler.shutdown()


